import * as detailsServices from './service'
import pathToRegexp from 'path-to-regexp'
export default {
	namespace: 'statecode_details',
	state: {
		code:[],
		list: [],
		pageState: {
			page: 1,
			total: null,
		},
  },

  subscriptions: {
    setup ({ dispatch, history }) {
			return history.listen (({ pathname, query }) => {
				//匹配动态路由地址
				const match = pathToRegexp('/statecode/details/:id').exec(pathname)
				if (match) {
					const { page,code } = query
					console.log(match[1])
					const pageParams = { page }
					dispatch ({ type: 'fetch', payload: { pageParams,id: match[1] }})
					dispatch ({ type: 'fetchCode', payload: { code }})
				}
			})
		},
  },

  reducers: {
		save ( state, { payload: { list, pageState} }) {
			return { ...state, list, pageState}
		},
		saveCode ( state, { payload}) {
			return { ...state,...payload }
		},
  },
  
  //异步请求
  effects: {
    *fetch ({ payload: { pageParams = {} } }, { call, put }) {
			// 1. 分页默认值 处理入参
			const { page = 1 } = pageParams
			const pagein = { currentpagenum: page }  //请求传入的参数对象
			// 2.请求表格数据并赋值
			const { body } = yield call(detailsServices.queryList, pagein)
			const { list, pageout } = body
			const pageState = { page: 1, total: pageout.rowcountall } //state中管理的分页对象
			yield put({ type: 'save', payload: { list, pageState } })
		},
		*fetchCode ({ payload}, { call, put }) {
			const {list} = yield call(detailsServices.codeSelect, payload)
			// console.log(list)
			yield put({ type: 'saveCode', payload: { code :list} })
		},
		*create ({ payload: values }, { call}) {
			yield call(detailsServices.create, values)
	   },
	*patch ({ payload: { id, values } }, { call, put }) {
			yield call(detailsServices.patch, { id, values })
			yield put({ type: 'reload' })
	   },
	*remove ({ payload: { id,user_name } }, { call, put }) {
			yield call(detailsServices.remove, { id, user_name})
			yield put({ type: 'reload' })
		},
		*reload (action, { put, select }) {
			const { list, pageState } = yield select(state => state.statecode_details.pageState)
			yield put({ type: 'fetch', payload: { list, pageState } })
	 },
  },  
}